package net.p2pcdn.realm;

import net.p2pcdn.user.domain.User;
import net.p2pcdn.user.domain.UserRole;
import net.p2pcdn.user.service.UserService;
import net.p2pcdn.util.MD5Util;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zx
 */
public class SystemAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;


    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        List<UserRole> userRoles = userService.getUserRoles(user.getId());
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        simpleAuthorInfo.addRoles(userRoles.stream().map(UserRole::getRoleCode).collect(Collectors.toList()));
        return simpleAuthorInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) auth;
        User user = userService.findByUsername(token.getUsername());
        if (user == null) {
            throw new AuthenticationException("用户名或密码错误");
        }
        if (!user.getPassword().equals(MD5Util.encryption(new String(token.getPassword())))) {
            throw new AuthenticationException("用户名或密码错误");
        }
        user.setPassword(null);
        return new SimpleAuthenticationInfo(user, token.getCredentials(), this.getName());
    }

}
